<template>
  <view class="page pageBg-color">

    <com-empty v-if="isEmpty && !isLoading"></com-empty>

    <view v-else>
      <view class="content">
        <view @click="goPreview(item._id)" v-for="item in dataList" :key="item._id" class="item">
          <image class="image" :src="item.smallPicurl" mode="aspectFill" lazy-load />
        </view>
      </view>
      <com-backTop :fixed="fixed"></com-backTop>
      <com-loadFooter :isHasMore="isHasMore" :isLoading="isLoading"></com-loadFooter>
    </view>

  </view>
</template>


<script lang="ts" setup>
import { ref } from 'vue';
import { onLoad, onPullDownRefresh, onReachBottom, onPageScroll } from '@dcloudio/uni-app';
import { API } from "@/services/api";
import { goHome } from '@/utils/utils';
import { useClassListStore } from "@/store";
const ClassListStore = useClassListStore();

const classid = ref(""); // 分类 ID
const wallListType = ref(""); // 类型：score 我的评分，download 我的下载
const dataList: any = ref([]); // 数据列表
const page = ref(1); // 页码
const isLoading = ref(false); // 加载状态
const isHasMore = ref(false); // 是否有更多数据可加载
const isEmpty = ref(true); // 数据是否为空

const fixed = ref(false); // 刷新、返回顶部 按钮的显示

// 监听页面加载
onLoad((options: any) => {
  if (Object.keys(options).length === 0) {
    console.log('~~~页面加载失败：未接收到任何参数');
    goHome();
    return;
  }

  const { id, name, type } = options; // 解构赋值
  if (name) uni.setNavigationBarTitle({ title: name }); // 设置导航栏标题

  if (id && name) {
    classid.value = id;
    getData();
  } else if (type && name) {
    wallListType.value = type;
    getData();
  } else {
    console.log('~~~未接收到需要的参数');
    goHome();
  }
});

// 监听用户下拉动作
onPullDownRefresh(() => {
  onRefresh();
});

// 页面滚动到底部的事件
onReachBottom(() => {
  if (isHasMore.value) {
    getData();
  }
});

// 监听页面滚动
onPageScroll((e) => {
  fixed.value = e.scrollTop > 200;
});

// 用户下拉执行需要执行的函数
const onRefresh = () => {
  dataList.value = [];
  page.value = 1;
  ClassListStore.clearList();
  getData();
};

// 获取接口数据
const getData = () => {
  isLoading.value = true;

  let res;
  if (classid.value) res = API.wallList(classid.value, page.value, 12);
  if (wallListType.value) res = API.userWallList(wallListType.value, page.value, 12);

  res?.then((res: any) => {
    console.log(`~~~获取 page = ${page.value} 的数据`);
    let newList = [...dataList.value];
    if (page.value === 1) newList = [];
    dataList.value = newList.concat(res.data || []);
    isLoading.value = false;
    isHasMore.value = res.data && res.data.length >= 12;
    isEmpty.value = dataList.value.length <= 0;
    page.value++;
    ClassListStore.setList(dataList.value);
  })
    .catch(() => {
      isLoading.value = false;
      isHasMore.value = false;
      isEmpty.value = true;
    })
};

// 去到预览页面
const goPreview = (id: string) => {
  uni.navigateTo({
    url: `/pages/pkgB/typePreview/index?id=${id}`
  })
};
</script>


<style lang="scss" scoped>
@use "style.scss";
</style>